<?php

class UserLogin {
	
	private $isLogin = false;
	private $data;
	
	function __construct($memories = true){

		if (isset($_POST['login'], $_POST['password']) && trim($_POST['login'],"\x00..\x1F")!=""&& trim($_POST['password'],"\x00..\x1F")!=""){
			
			$login = strtolower($_POST['login']);
	
			$query="SELECT * FROM tb_users WHERE lower(login)='{$login}'\n";
			
			$result = mysql_query($query);
			
			$data = mysql_fetch_object($result);
			
			if(is_object($data) && $data->id != "" && $data->password == $_POST['password']){
				
				$this->data = $data;
				$this->isLogin = true;
				$time_cookie = ($memories)? time()+604800 : null;
				
				$md5_coockie = array('id' => $data->id, 'md5_pass' => md5($data->password), 'memories' => (int)$memories);
				$md5_coockie = serialize($md5_coockie);
				setcookie("user_data", $md5_coockie, $time_cookie,  '/', '.' . SITE_HOST);				
			}
		}
		elseif(isset($_COOKIE['user_data'])){
			
			$array = unserialize(stripslashes(stripslashes($_COOKIE['user_data'])));
			
			if(is_numeric($array['id']) && $array['id']>0){
				
				$query = "SELECT *, md5(password) as mdpassword FROM tb_users WHERE id='{$array['id']}'";
				$result=mysql_query($query);
				$data=mysql_fetch_object($result);
				
				if($array['md5_pass'] != $data->mdpassword){
					$this->logout(true);
				}
				else{
					$this->isLogin = true;
				}
			}
			
			if(!is_object($data) || $data->mdpassword != $array['md5_pass'] || $data->mdpassword == ''){
				$this->logout(true);
			}
			else {
				
				$this->data = $data;
				
				$time_cookie=((int)$array['memories'])?time()+604800:null;//
			
				$md5_coockie=array('id'=>$data->id, 'md5_pass'=>$data->password, 'memories'=>(int)$memories);
				
				$md5_coockie=serialize($md5_coockie);					
					
			}
			
		}
	}

	/**
	 * Check is login
	 *
	 * @return bool
	 */
	public function isLogin(){
		return $this->isLogin;
	}
	
	public function getData(){
		return $this->data;
	}
	
	public function logout($expired = false){
		
		$this->data = null;
		$this->isLogin = false;
		($expired)?
			setcookie("user_data", "", time()-604800, '/', '.' . SITE_HOST)
			:
			setcookie("user_data", "", null, '/', '.' . SITE_HOST);
		
		header("Location:/");
	}
}

?>